//
//  HHToolsViewController.m
//  wanNengMiMa
//
//  Created by HappyMilk 01 on 2017/3/2.
//  Copyright © 2017年 HappyMilk 01. All rights reserved.
//

#import "HHToolsViewController.h"
#import "STDPingServices.h"
#import "WifiHeader.h"

@interface HHToolsViewController ()
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITextView *textView;


@property (nonatomic,strong) STDPingServices *pingServices;

@property BOOL isPing;

@end

@implementation HHToolsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    _textField.placeholder = K_NSLOCAL(@"Enter IP address or domain");
    [self initTextView];
   
}
- (IBAction)popvc:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)initTextView{
    self.textView.editable=false;
    
    self.textView.backgroundColor = [UIColor blackColor];
    self.textView.textColor = [UIColor greenColor];
}

- (IBAction)okBtnClicked:(UIButton *)sender {
    [_textField resignFirstResponder];
    
    if(self.isPing){
        [sender setTitle:@"Ping" forState:0];
        self.isPing = false;
        
        _pingServices=nil;
        return ;
    }
    
    _textView.text = @"";
    
    [sender setTitle:@"Stop" forState:0];
    self.isPing = true;
    
    NSString *address = self.textField.text;
    
    __weak HHToolsViewController *weakSelf = self;
    
    _pingServices=[STDPingServices startPingAddress:address callbackHandler:^(STDPingItem *pingItem, NSArray *pingItems) {
        
        [weakSelf showResult:pingItem.description];
        
        
        weakSelf.textView.text = [NSString stringWithFormat:@"%@\n\n",weakSelf.textView.text];
         [weakSelf.textView scrollRangeToVisible:NSMakeRange(weakSelf.textView.text.length, 100)];
        
        
        if(pingItem.status==STDPingStatusFinished  || pingItem.status==STDPingStatusError){
            [sender setTitle:@"Ping" forState:0];
            weakSelf.isPing = false;
            weakSelf.pingServices=nil;
        }
        
        if(pingItem.status==STDPingStatusDidFailToSendPacket){
//            weakSelf.pingServices
            [weakSelf.pingServices cancel];
            weakSelf.pingServices = nil;
        }
        
    }];
    
    
    
}



-(void)showResult:(NSString *)str{
    for(int i=0;i<str.length;i++){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(i * NSEC_PER_SEC/100)), dispatch_get_main_queue(), ^{
            _textView.text=[NSString stringWithFormat:@"%@%c",_textView.text,[str characterAtIndex:i]];
        });
        
    }
}


@end
